/**
 * 
 */
package com.base.myproject.client.busi.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseStoreEvent;
import com.base.myproject.client.busi.BaseStoreListener;
import com.base.myproject.client.busi.JDBCModelData;
import com.base.myproject.client.busi.BaseStoreEvent.EventType;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseToolBar;
import com.base.myproject.client.ui.Toolbar;
import com.base.myproject.client.ui.Model.TreeModel;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.dnd.GridDragSource;
import com.extjs.gxt.ui.client.dnd.GridDropTarget;
import com.extjs.gxt.ui.client.dnd.DND.Feedback;
import com.extjs.gxt.ui.client.dnd.DND.Operation;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ToggleButton;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.ListField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGrid;
import com.extjs.gxt.ui.client.widget.treegrid.TreeGridCellRenderer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * 菜单权限
 * 
 * @author zgw 2009-7-10 下午04:12:59 javazgw@gmail.com
 */
public class MenuPermissions extends LayoutContainer implements Toolbar {
	static BaseStore<JDBCModelData> store = null;
	BaseStore<BaseModelData> groupstore = null;
	BaseStore<JDBCModelData> tostore = null;
	ListField to = null;
	private GridDropTarget target;
	private GridDropTarget target2;
	BaseStore<ModelData> tarstore = null;
	static Grid grid2 = null;
	TreeGrid<ModelData> tree;
	
	 static java.util.LinkedList<Component>  toolbarll = new java.util.LinkedList<Component>();

	public MenuPermissions() {
		init();
		this.setScrollMode(Scroll.AUTO);
	}

	public void init() {
		setLayout(new ColumnLayout());
		// this.add(CreateListView());
		add(CreateTreaPanel());
		// this.add(CreateFormPanel());
		Grid grid1 = CreateGrid();
		// grid2 =
		CreatetarGrid();
		grid2.setLoadMask(false);
		new GridDragSource(grid1);
		// new GridDragSource(grid2);
		target = new GridDropTarget(grid1);
		target.setAllowSelfAsSource(false);

		target2 = new GridDropTarget(grid2);
		target2.setAllowSelfAsSource(false);
		Feedback f = Feedback.BOTH;
		target.setFeedback(f);
		target2.setFeedback(f);
		target.setOperation(Operation.COPY);
		target2.setOperation(Operation.COPY);
		FieldSet fs = new FieldSet();
		fs.setHeading("菜单权限分配");
		fs.setLayout(new ColumnLayout());
		Html html = new Html();
		html.setHtml("<a>请从左边的窗口拖动组到右边的窗口！进行权限分配。");
		fs.add(grid1);
		fs.add(grid2);
		fs.add(html);

	

		add(fs);
		initToolBarItems();
		

	}
	
	public void initToolBarItems() {
		Button save = new Button("保存");
		save.setIconStyle("disk_black");
		save.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub

			
				String[][] strarr = new String[2][];
				strarr[0] = new String[tarstore.getCount()];
				strarr[1] = new String[tree.getSelectionModel()
						.getSelectedItems().size()];
				for (int i = 0; i < tarstore.getCount(); i++) {
			
					strarr[0][i] = tarstore.getValue(i, "groupicode")
							.toString();
				}

				for (int i = 0; i < tree.getSelectionModel().getSelectedItems()
						.size(); i++) {
			
					strarr[1][i] = tree.getSelectionModel().getSelectedItems()
							.get(i).get("menucode");
				}
				GreetingServiceAsync greetingService = GWT
						.create(GreetingService.class);
				greetingService.greetServer(strarr, "z",
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								caught.printStackTrace();
								
							}

							public void onSuccess(String result) {
								// System.out.println(result.length);
							
							}
						});
			}

		});
//		toolbarll.add(save);
//		initToolBar();
		toolbarll.add(save);
	
	}
	public void initToolBar() {
		BaseToolBar.getInstance().removeAll();
		BaseToolBar.getInstance().add(new SeparatorToolItem());
		// BaseToolBar.getInstance().getItems().clear();
		// BaseToolBar.getInstance().add(new TextToolItem("save") );
		// BaseToolBar.getInstance().add(new TextToolItem("save1") );
		for (int i = 0; i < toolbarll.size(); i++) {
			
			BaseToolBar.getInstance().add(toolbarll.get(i));
		}
		BaseToolBar.getInstance().add(new SeparatorToolItem());
		

	}

	/*
	 * public FormPanel CreateFormPanel() { FormPanel panel = new FormPanel();
	 * CreateStore(); panel.setHeading("Drag and Drop Lists");
	 * 
	 * final DualListField lists = new DualListField();
	 * 
	 * lists.setFieldLabel("Stocks"); ListField from = lists.getFromList();
	 * 
	 * from.setDisplayField("groupname");
	 * 
	 * store.setStoreSorter(new StoreSorter()); //
	 * store.add(TestData.getShortStocks()); from.setStore(store); to =
	 * lists.getToList(); to.setDisplayField("groupicode"); tostore = new
	 * BaseStore<JDBCModelData>(); tostore.setStoreSorter(new StoreSorter());
	 * to.setStore(tostore);
	 * 
	 * 
	 * Button Save = new Button("保存"); Save.setIconStyle("disk_black");
	 * Save.addSelectionListener(new SelectionListener() { public void
	 * componentSelected(ComponentEvent ce) {
	 * 
	 * } }); panel.add(lists, new FormData("100%")); from.setHeight(400);
	 * to.setHeight(400); lists.setHeight(400); panel.setHeight(400);
	 * panel.setAutoWidth(true); panel.setButtonAlign(HorizontalAlignment.LEFT);
	 * panel.addButton(Save); return panel; } public void CreateStore() {
	 * ModelType type = new ModelType(); type.setRoot("records");
	 * type.setRecordName("record");
	 * 
	 * type.addField("groupicode"); type.addField("groupname"); //
	 * type.addField("Phone"); // type.addField("imagepath"); StoreInfo info =
	 * new StoreInfo(); info.setTablename("basegroup");
	 * info.setSql("select * from basegroup"); store= new
	 * BaseStore<JDBCModelData>(type, info);
	 * 
	 * }
	 */
	void CreateGroupStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("menucode");
		type.addField("menuname");
		// type.addField("Phone");
		// type.addField("imagepath");
		StoreInfo info = new StoreInfo();
		info.setTablename("menu");
		info.setSql("select * from menu");
		groupstore = new BaseStore<BaseModelData>(type, info);

	}

	/*
	 * ContentPanel CreateListView() { ContentPanel layoutcontainer = new
	 * ContentPanel(); CreateGroupStore(); final CheckBoxListView<BaseModelData>
	 * view = new CheckBoxListView<BaseModelData>() {
	 * 
	 * @Override protected BaseModelData prepareData(BaseModelData model) {
	 * String s = model.get("menuname").toString(); model.set("shortName",
	 * Format.ellipse(s, 15)); return model; }
	 * 
	 * }; view.setDisplayProperty("menuname"); view.setStore(groupstore);
	 * layoutcontainer .add(view); view.setAutoHeight(true);
	 * view.setAutoWidth(true); layoutcontainer.setWidth(300);
	 * 
	 * 
	 * 
	 * return layoutcontainer; }
	 */
	ContentPanel CreateTreaPanel() {
		final ContentPanel cp = new ContentPanel();
		ToolBar toolBar = new ToolBar();
		final ToggleButton toggleBtn = new ToggleButton("全部展开");
		toggleBtn.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				System.out.println(toggleBtn.isPressed());
				if(toggleBtn.isPressed())
				{
					toggleBtn.setText("全部展开");
				
				}
				else{
					toggleBtn.setText("全部关闭");
				}
			}
			
		});
		toggleBtn.toggle(true);
		toolBar.add(toggleBtn);

	//	cp.setTopComponent(toolBar);

		final TreeStore<ModelData> store = new TreeStore<ModelData>();
		GreetingServiceAsync greetingService = GWT
				.create(GreetingService.class);
		greetingService.greetServerarr("zzz", new AsyncCallback<String[][]>() {
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				caught.printStackTrace();
			}

			public void onSuccess(String[][] result) {
				
				TreeModel treemodel = TreeModel.get123(result);
				store.add(treemodel.getChildren(), true);
				CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();

				// TreeModel treemodel = TreeModel.get123();
				// System.out.println("list size"+
				// treemodel.getChildren().size());
				// store.add( treemodel.getChildren(), true);
				ColumnConfig name = new ColumnConfig("menucode", "菜单编号", 100);
				name.setRenderer(new TreeGridCellRenderer<ModelData>());

				ColumnConfig date = new ColumnConfig("menuname", "菜单名", 100);

				
				ColumnModel cm = new ColumnModel(Arrays.asList(cbs.getColumn(),
						name, date));

				tree = new TreeGrid<ModelData>(store, cm);
				tree.setBorders(true);
				// tree.getStyle().setLeafIcon(Examples.ICONS.music());
				tree.setSize(400, 400);
				tree.setAutoExpandColumn("menucode");
				tree.setTrackMouseOver(false);
				cbs.setSelectionMode(SelectionMode.MULTI);
				tree.setSelectionModel(cbs);
				tree.getSelectionModel().addSelectionChangedListener(
						new SelectionChangedListener() {

							@Override
							public void selectionChanged(
									SelectionChangedEvent se) {
								// TODO Auto-generated method stub
						

								ModelType type = new ModelType();
								type.setRoot("records");
								type.setRecordName("record");

								type.addField("menucode");
								type.addField("groupicode");
								type.addField("nemuname");
								// type.addField("Phone");
								// type.addField("imagepath");
								StoreInfo info = new StoreInfo();
								info.setTablename("menupermissions");
								info
										.setSql("select * from menupermissions where menucode='"
												+ se.getSelectedItem().get(
														"menucode") + "'");
								tarstore = new BaseStore<ModelData>(type, info);

								tarstore.getLoader().addLoadListener(
										new LoadListener() {
											public void loaderLoad(LoadEvent le) {
												
												// to.setStore(tostore);
												// to.getListView().refresh();
												// to.getListView().repaint();
												// tarstore.removeAll();
												// grid2.recalculate();
												// grid2.setStore(tarstore);
												// grid2.getView().layout();
												// grid2.setStore(tarstore);
												// grid2.getView().refresh(true);
												
											//	System.out.println(grid2);
												grid2.reconfigure(tarstore,
														grid2.getColumnModel());

											}
										});
							}

						});

				cp.add(tree);
				cp.layout();
			}
		});
		
		
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		cp.setLayout(new FitLayout());
		
		cp.setSize(600, 300);
		return cp;
	}

	Grid CreateGrid() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("groupicode");
		type.addField("groupname");
		// type.addField("Phone");
		// type.addField("imagepath");
		StoreInfo info = new StoreInfo();
		info.setTablename("basegroup");
		info.setSql("select * from basegroup");
		BaseStore<ModelData> basegroupstore = new BaseStore<ModelData>(type,
				info);

		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		// columns.add(cbs.getColumn());
		ColumnConfig groupname = new ColumnConfig("groupname", "可使用组名称", 100);

		columns.add(groupname);

		ColumnModel cm = new ColumnModel(columns);
		Grid grid = new Grid(basegroupstore, cm);
		grid.setWidth(200);
		grid.setHeight(400);
		grid.setStyleAttribute("margin", "10px");
		grid.setBorders(true);
		return grid;
	}

	void CreatetarGrid() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("menucode");
		type.addField("groupicode");
		type.addField("nemuname");
		// type.addField("Phone");
		// type.addField("imagepath");
		StoreInfo info = new StoreInfo();
		info.setTablename("menupermissions");
		info.setSql("select * from menupermissions");

		tarstore = new BaseStore<ModelData>(type, info);
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		final ColumnConfig groupname = new ColumnConfig("groupicode", "权限组名称",
				100);

		// -----------
		ModelType typer = new ModelType();
		typer.setRoot("records");
		typer.setRecordName("record");

		typer.addField("groupicode");
		typer.addField("groupname");

		// type.addField("Phone");
		// type.addField("imagepath");
		StoreInfo infor = new StoreInfo();
		infor.setTablename("basegroup");
		infor.setSql("select * from basegroup");

		final BaseStore<ModelData> tarstorer = new BaseStore<ModelData>(typer,
				infor);

		// -----------

		tarstorer.addBaseStoreListener(EventType.LOAD_COMPLETE,
				new BaseStoreListener() {

					@Override
					public void BaseStoreEventHandle(BaseStoreEvent evt) {

						final java.util.Map<String, String> ht = new java.util.HashMap<String, String>();
						for (int i = 0; i < tarstorer.getModels().size(); i++) {
							ht.put(tarstorer.getModels().get(i).get(
									"groupicode").toString(), tarstorer
									.getModels().get(i).get("groupname")
									.toString());

						}
						GridCellRenderer<ModelData> renderer = new GridCellRenderer<ModelData>() {

							public String render(ModelData model,
									String property, ColumnData d,
									int rowIndex, int colIndex,
									ListStore<ModelData> store,
									Grid<ModelData> grid) {

								
								return ht.get(model.get(property));
							}
						};
						groupname.setRenderer(renderer);
					}

					@Override
					public void onBrowserEvent(Event event) {
						// TODO Auto-generated method stub

					}

				});

		columns.add(groupname);

		ColumnModel grid2cm = new ColumnModel(columns);
		grid2 = new Grid(tarstore, grid2cm);

		grid2.setWidth(200);
		grid2.setHeight(400);
		grid2.setStyleAttribute("margin", "10px");
		grid2.setBorders(true);

	}

}
